<template>
  <div class="book-form-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑图书' : '添加图书' }}</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form
        ref="bookFormRef"
        :model="bookForm"
        :rules="rules"
        label-width="100px"
        :disabled="loading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图书名称" prop="name">
              <el-input v-model="bookForm.name" placeholder="请输入图书名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="bookForm.author" placeholder="请输入作者" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出版社" prop="publisher">
<!--              <el-input v-model="bookForm.publisher" placeholder="请输入出版社" />-->
                <el-select v-model="bookForm.publisher" placeholder="请选择出版社" style="width: 100%">
                  <el-option
                      v-for="item in publisherOptions"
                      :value="item"
                  />
                </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出版日期" prop="publishDate">
              <el-date-picker
                v-model="bookForm.publishDate"
                type="date"
                placeholder="请选择出版日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ISBN" prop="isbn">
              <el-input v-model="bookForm.isbn" placeholder="请输入ISBN编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="bookForm.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number
                v-model="bookForm.price"
                :precision="2"
                :step="0.01"
                :min="0"
                style="width: 100%"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input-number
                v-model="bookForm.stock"
                :min="0"
                :step="1"
                style="width: 100%"
                placeholder="请输入库存数量"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="存放位置" prop="location">
              <el-input v-model="bookForm.location" placeholder="请输入存放位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面图片" prop="coverImage">
              <el-input v-model="bookForm.coverImage" placeholder="请输入封面图片URL" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="图书描述" prop="description">
          <el-input
            v-model="bookForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入图书描述"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">{{ isEdit ? '保存修改' : '添加图书' }}</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getBookDetail, addBook, updateBook } from '../../api/book'
import { getAllCategories } from '../../api/category'
import {getAllPublishers} from "@/api/publisher";

const route = useRoute()
const router = useRouter()

// 判断是否为编辑模式
const isEdit = computed(() => {
  return !!route.params.id
})

// 表单引用
const bookFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 图书表单数据
const bookForm = reactive({
  id: undefined,
  name: '',
  author: '',
  publisher: '',
  publishDate: '',
  isbn: '',
  categoryId: undefined,
  description: '',
  price: undefined,
  stock: 0,
  location: '',
  coverImage: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入图书名称', trigger: 'blur' },
    { min: 1, max: 100, message: '图书名称长度不能超过100个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' },
    { min: 1, max: 50, message: '作者长度不能超过50个字符', trigger: 'blur' }
  ],
  isbn: [
    { required: true, message: '请输入ISBN编号', trigger: 'blur' },
    { min: 1, max: 20, message: 'ISBN长度不能超过20个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  price: [
    { required: false, message: '请输入价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  publisher: [{ required: true, message: '请选择出版社', trigger: 'change' }]
}

// 分类选项
const categoryOptions = ref([])
const publisherOptions = ref([])

// 获取所有分类
const fetchCategories = async () => {
  try {
    const res = await getAllCategories()
    if (res.data) {
      categoryOptions.value = res.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

const fetchPublishers = async () => {
  try {
    const res = await getAllPublishers()
    if (res.data) {
      publisherOptions.value = res.data || []
    }
  } catch (error) {
    console.error('获取出版社列表失败:', error)
    ElMessage.error('获取出版社列表失败')
  }
}

// 获取图书详情
const getDetail = async (id) => {
  loading.value = true
  try {
    const res = await getBookDetail(id)
    if (res.data) {
      // 将后端返回的数据填充到表单中
      Object.assign(bookForm, res.data)
    }
  } catch (error) {
    console.error('获取图书详情失败:', error)
    ElMessage.error('获取图书详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!bookFormRef.value) return
  
  await bookFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (isEdit.value) {
          // 编辑模式
          await updateBook(bookForm)
          ElMessage.success('修改成功')
        } else {
          // 添加模式
          await addBook(bookForm)
          ElMessage.success('添加成功')
        }
        // 返回列表页
        goBack()
      } catch (error) {
        console.error(isEdit.value ? '修改图书失败:' : '添加图书失败:', error)
        ElMessage.error(isEdit.value ? '修改图书失败' : '添加图书失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (!bookFormRef.value) return
  
  bookFormRef.value.resetFields()
  if (isEdit.value) {
    // 编辑模式下重新获取详情
    getDetail(route.params.id)
  }
}

// 返回列表页
const goBack = () => {
  router.push('/book')
}

// onMounted(async () => {
//   // 获取分类列表
//   await fetchCategories()
//
//   // 如果是编辑模式，获取图书详情
//   if (isEdit.value && route.params.id) {
//     await getDetail(route.params.id)
//   }
// })
onMounted(async () => {
  // 获取分类和出版社列表
  await Promise.all([fetchCategories(), fetchPublishers()])

  // 如果是编辑模式，获取图书详情
  if (isEdit.value && route.params.id) {
    await getDetail(route.params.id)
  }
})
</script>

<style scoped>
.book-form-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>